package com.two.screen.water.balance.ui.activity

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import cn.jpush.android.api.JPushInterface
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.google.gson.reflect.TypeToken
import com.jakewharton.rxbinding2.view.RxView
import com.lzy.okgo.OkGo
import com.lzy.okrx2.adapter.ObservableBody
import com.two.screen.water.balance.R
import com.two.screen.water.balance.bean.*
import com.two.screen.water.balance.bean.database.UserDB
import com.two.screen.water.balance.image.ImageManger
import com.two.screen.water.balance.listener.ApiCallBack
import com.two.screen.water.balance.listener.MyObserver
import com.two.screen.water.balance.net.JsonConvert
import com.two.screen.water.balance.net.api.CateProductApi
import com.two.screen.water.balance.net.api.DBApi
import com.two.screen.water.balance.net.api.DataApi
import com.two.screen.water.balance.net.api.NormalApi
import com.two.screen.water.balance.net.observer.DialogObserver
import com.two.screen.water.balance.permission.PermissionUtil
import com.two.screen.water.balance.print.PrinterAll
import com.two.screen.water.balance.ui.App
import com.two.screen.water.balance.ui.activity.base.BaseActivity
import com.two.screen.water.balance.ui.service.AppService
import com.two.screen.water.balance.utils.*
import com.two.screen.water.balance.utils.eventbus.Event
import com.two.screen.water.balance.utils.eventbus.EventBusUtil
import com.two.screen.water.balance.utils.eventbus.EventCode
import com.two.screen.water.balance.serial.weight.SerialPortWeightZzUtils
import com.two.screen.water.balance.widget.dialog.LoadingDialog
import io.reactivex.Observable
import io.reactivex.ObservableOnSubscribe
import kotlinx.android.synthetic.main.activity_login.*
import java.util.concurrent.TimeUnit


@Route(path = ARouterUtils.LoginActivity)
class LoginActivity : BaseActivity() {
    val TAG = LoginActivity::class.java.simpleName.plus("=>")
    var loadingDialog: LoadingDialog? = null
    var mLoginDialog: AlertDialog.Builder? = null
    var mChooseBrandDialog: AlertDialog.Builder? = null
    private var tel: String? = null
    private var pwd: String? = null
    private var mCount = 0
    private var mIsShowDeviceSnQrCode = false

    @Autowired @JvmField var mIsAutoLogin = false


    override fun getContentLayout(): Any = R.layout.activity_login

    override fun beforeSetContentView() {
        App.flag = 0
    }

    override fun initView(savedInstanceState: Bundle?) {
        ARouter.getInstance().inject(this)
        //startService(Intent(this, LocalService::class.java))
        mRememberCbx.isChecked = SPUtils.getBoolean(Params.isRememberPwd)

        //initBaseUrl()

        initViceScreen()
        DBApi.initLocalAccount(this)

        PermissionUtil.requestPermission(this@LoginActivity, PermissionUtil.READ_PHONE_STATE, {
            d("授权成功?")
        })

        if (!PrinterAll.isPrintConnectSuccess()) {
            PrinterAll.printerInit()
        }
    }


    /*副屏显示*/
    private fun initViceScreen() {
        if (!DataApi.mIsShowViceDisplay) return
        PermissionUtil.requestPermissionForAlertWindow(this@LoginActivity, {
//            mPresentationPresenter = PresentationPresenter()
//            mPresentationPresenter?.openViceScreen(this)
            d("initViceScreen:")
            DataApi.logoutViceScreenDisplayData()
            EventBusUtil.sendEvent(Event(EventCode.SHOW_OTHER_DISPLAY))
        })
    }

    override fun initData() {
        ImageManger.setLogoBlue(this, mLogoIv, SPUtils.getLogoBlue())
        CommUtils.checkUpdateApp01(this)
        mVersionNameTv?.text = "版　本：".plus(CommUtils.getAppVersionName()).plus("\n设备号：").plus(CommUtils.getAppUUid())
        mVersionNameTv?.setOnClickListener {
            mIsShowDeviceSnQrCode = !mIsShowDeviceSnQrCode
            mDeviceCodeQrIv.visibility = if (mIsShowDeviceSnQrCode) View.VISIBLE else View.GONE
        }
        //var qrMap = sortedMapOf("v" to CommUtils.getAppVersionName(), "s" to CommUtils.getAppUUid())
        mDeviceCodeQrIv.setImageBitmap(
            ZXingUtils.createQRCodeBitmap(
                CommUtils.getAppUUid(), 500, "UTF-8", "H", "0", Color.BLACK, Color.WHITE, null, null, 0.2f
            )
        )

        tel = SPUtils.getAccountTel()//"15602983384"//DBApi.DEFAULT_ACCOUNT//SPUtils.getAccountTel()
        pwd = SPUtils.getAccountPwd()//"123123"//DBApi.DEFAULT_PASSWORD//SPUtils.getAccountPwd()
        //保证重启app，数据没更新。
        mLoginTelEt?.setText(tel)
        mLoginTelEt?.setSelection(tel?.length ?: 0)

        mLoginPasswordEt?.setText(pwd)
        mLoginPasswordEt?.setSelection(pwd?.length ?: 0)

        mLoginTv?.let {
            RxView.clicks(it)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe {
                    //onLoginClick()
                    SerialPortWeightZzUtils.setPeel()
                }
        }
//        d("xor1:${CommUtils.calcHexXorInvert("004C08000F020000000103")}")//这个是 加载密钥KeyA
//        d("xor2:${CommUtils.calcHexXorInvert("001203000f04")}")//这个是 这个访问block04
//        d("xor3:${CommUtils.calcHexXorInvert("00F600")}")//这个是 密钥验证错误
//        d("xor4:${CommUtils.calcHexXorInvert("00100100")}")//这个是 询问卡id  2000100100XX03  ->2000100100EE03
        d("xor5:${CommUtils.calcHexXorInvert("00 52 00")}")//这个是 初始化  20005200XX03  ->20005200AD03
        d("xor6:${CommUtils.calcHexXorInvert("00 10 01 01")}")//
        d("xor7:${CommUtils.calcHexXorInvert("00 00 08 08 00 20 04 5A 1B 69 29")}")//
        d("xor8:${CommUtils.calcHexXorInvert("00100100")}")//
//        mTestKeyInputEt.setOnKeyListener { v, keyCode, _ ->
////            d("来自哪里输入：${event.device.name}")
////            // 检查是否是你想要处理的按键事件
////            if (event.action == KeyEvent.ACTION_DOWN) {
////                // 处理按键事件
////                KeyboardUtil.onKeyDown(keyCode, event, null, v)
////            } else false
//            true
//        }
//        mTestKeyInputEt.onFocusChangeListener = View.OnFocusChangeListener { v, hasFocus ->
//            d("hasFocus:$hasFocus")
//            if (hasFocus) hideSoftKeyBoard()
//        }
    }


    @SuppressLint("CheckResult")
    override fun initListener() {
        RxView.clicks(mSettingIv)
            .throttleFirst(1, TimeUnit.SECONDS)
            .subscribe {
//                unregisterReceiver(getBatteryChangedReceiver)
                ARouter.getInstance()
                    .build(ARouterUtils.SystemSettingActivity)
                    .navigation()

            }
//        mLoginTv.setOnLongClickListener {
//            //CateProductApi.initCateProductData()
//            //ToastUtil.showToast("测试菜品添加成功!")
//            false
//        }

        RxView.clicks(mForgetPwdTv)
            .throttleFirst(1, TimeUnit.SECONDS)
            .subscribe {
                ARouter.getInstance()
                    .build(ARouterUtils.ForgetPwdActivity)
                    .navigation()
            }

        mRememberCbx.setOnCheckedChangeListener { cbx, isCheck ->
            d("isRemember:$isCheck")
            SPUtils.putBoolean(Params.isRememberPwd, isCheck)
        }

//        mForgetPwdTv.postDelayed({
//            ARouter.getInstance()
//                .build(ARouterUtils.IndexActivity)
//                .navigation()
//        }, 2000)

        //TODO:测试读卡器
//        ReaderAll.startReadCard()
//        mRememberCbx.postDelayed(Runnable {
//            ReaderAll.stopReadCard()
//        }, 5000)
        d("mIsAutoLogin:$mIsAutoLogin")
        if (mIsAutoLogin) {
            mLoadingDialog.show()
            mLoadingDialog.titleTv.text = "准备登陆..."
            mLoginTv?.postDelayed({
                mLoadingDialog.dismiss()
                onLoginClick()
            }, 2500)
        }
    }

    private fun onLoginClick() {

        //TODO:帐号密码
        var mTel = mLoginTelEt?.text.toString()
        var mPwd = mLoginPasswordEt?.text.toString()

        if (mTel.isBlank()) {
            ToastUtil.showToast("手机号不能为空！")
            return
        }

        if (mPwd.isBlank()) {
            ToastUtil.showToast("密码不能为空！")
            return
        }

        if (mTel == "29658888" && mPwd == "29658888") {
            finish()
        } else {
            //TODO:这里暂时放弃离线情况。
            if (DataApi.mIsConnectNet) {
                d("Urls.login：${Urls.login}")
                NormalApi.getLoginData(sortedMapOf(Params.sc_n to CommUtils.getAppUUid()/*"106A8798EF99E310"*/, Params.username to mTel, Params.password to CommUtils.encodeByMD5(mPwd)), Urls.login)
                    .compose(RxUtils.aLifecycle(this@LoginActivity))
                    .subscribe(object : DialogObserver<LoginBean>(this@LoginActivity, "正在登录...") {
                        override fun onSuccessNext(t: BaseBean<out LoginBean>) {
                            loginSuccess(t, mTel, mPwd)
                        }
                    })
            } else {
                //离线
                //ToastUtil.showToast("请检查网络!")
                loginSuccessOffline(mTel, mPwd)
            }
            //loginSuccess(null, mTel, mPwd)
        }
    }

    private fun setUserUpdateTime(userDB: UserDB) {
        if (userDB.updateTime == null) {
            Observable.create(ObservableOnSubscribe<String> { e ->
                //已交接
                userDB.updateTime = System.currentTimeMillis() / 1000
                userDB.updateTimeName = CommUtils.toYMD_HMS(userDB.updateTime)
                App.mDaoSession?.userDBDao?.update(userDB)
                e.onNext("")
            })
                .compose(RxUtils.io())
                .compose(RxUtils.aLifecycle(this@LoginActivity))
                .subscribe(object : MyObserver<String>() {
                    override fun onNext(t: String) {
                    }
                })
        }
    }

    private fun loginSuccessOffline(mTel: String, mPwd: String) {
        DBApi.getLogin(this@LoginActivity, mTel, mPwd, object : ApiCallBack() {
            override fun success(t: Any?, indexBean: IndexBean?, serverGoods: ServerGoods?) {
                var userDB = t as UserDB
                DataApi.mShopLogoUrl = userDB.logo
                DataApi.mToken = userDB.token
                DataApi.mIsWeight = userDB.isWeight == 1// 0 不允许 1 允许
                DataApi.mUserId = userDB.userId
                DataApi.mUserName = userDB.userName
                DataApi.mPayButtonList = try {
                    CommUtils.gson.fromJson(userDB.payButtonJson, object : TypeToken<List<PayButton>>() {}.type)
                } catch (e: Exception) {
                    mutableListOf(PayButton().apply { pay_id = 1;title = "现金支付" })
                }
                SPUtils.putString(Params.user_id, DataApi.mUserId)
                SPUtils.putString(Params.mar_id, userDB.circleId)
                //EventBusUtil.sendEvent(Event(EventCode.AI_RECOGNITION_INIT))
                val jPushAlias = CommUtils.encodeByMD5(DataApi.mAppUnitId).lowercase()
                d("jPushAlias:$jPushAlias,mAppUnitId:${DataApi.mAppUnitId}")
                JPushInterface.setAlias(App.context, 0, jPushAlias)
                setUserUpdateTime(userDB)//在线是直接创建，所以无需更新时间

                indexBean?.let { DataApi.updateData(it) }
                serverGoods?.let { CateProductApi.initCateProductData(it, this@LoginActivity) }
                ARouter.getInstance()
                    .build(ARouterUtils.IndexActivity)
                    .navigation()
                finish()
            }
        })
    }

    private fun loginSuccess(t: BaseBean<out LoginBean>, mTel: String, mPwd: String) {
        var data = t.data
        DBApi.insertNewAccount(data, mTel, mPwd, this)
        if (mRememberCbx.isChecked) {
            SPUtils.rememberAccount(mTel, mPwd)
        } else {
            SPUtils.rememberAccount(null, null)
        }
        if (data?.token?.isNotBlank() == true) {
            DataApi.mShopLogoUrl = data.user_info?.header
            DataApi.mToken = data.token
            DataApi.mIsWeight = data.is_weight == 1// 0 不允许 1 允许
            DataApi.mUserId = data.user_info?.id
            DataApi.mUserName = data.user_info?.name
            DataApi.mPayButtonList = data.pay_button ?: mutableListOf(PayButton().apply { pay_id = 1;title = "现金支付" })
            SPUtils.putString(Params.user_id, DataApi.mUserId)
            SPUtils.putString(Params.mar_id, data.user_info?.circle_id)
            SPUtils.putLogoBlue(data.logo)
            val jPushAlias = CommUtils.encodeByMD5(DataApi.mAppUnitId).lowercase()
            d("jPushAlias:$jPushAlias,mAppUnitId:${DataApi.mAppUnitId}")
            //EventBusUtil.sendEvent(Event(EventCode.AI_RECOGNITION_INIT))
            JPushInterface.setAlias(App.context, 0, jPushAlias)
//            //获取配置信息
//            getDataInfo()
//            //商品信息
//            getDataGoodsList()
//            //等待请求完毕后跳转
//            pollingAskOK()

            initShopInfo()

        } else {
            loadingDialog?.dismiss()
            ToastUtil.showToast(t.msg)
        }

    }

    private fun initShopInfo() {
        //信息 Observable
        var getInfoCompose = OkGo.post<BaseBean<IndexBean>>(Urls.info) //
            .headers(Params.getHeads())
            .converter(object : JsonConvert<BaseBean<IndexBean>>() {}) //
            .adapt(ObservableBody()) //
            .compose(RxUtils.io())

        //商品 Observable
        var getGoodListCompose = OkGo.post<BaseBean<ServerGoods>>(Urls.goodsList) //
            .headers(Params.getHeads())
            .converter(object : JsonConvert<BaseBean<ServerGoods>>() {}) //
            .adapt(ObservableBody()) //
            .compose(RxUtils.io())

        Observable.zip(getInfoCompose, getGoodListCompose) { t1, t2 ->
            //信息
            if (t1.data != null) {
                SPUtils.putString(Params.IndexBeanJson.plus("_").plus(DataApi.mUserId), CommUtils.gson.toJson(t1.data!!))
                DataApi.updateData(t1.data!!)
            }
            //商品
            if (t2.data != null) {
                SPUtils.putString(Params.ServerGoodsJson.plus("_").plus(DataApi.mUserId), CommUtils.gson.toJson(t2.data!!))
                CateProductApi.initCateProductData(t2.data, this@LoginActivity)
            }
            Thread.currentThread().name
        }.compose(RxUtils.io())
            .doOnSubscribe {
                mLoadingDialog.show()
                mLoadingDialog.titleTv.text = "正在同步数据..."
            }
            .subscribe(object : MyObserver<String>() {
                override fun onNext(t: String) {
                    mLoadingDialog.dismiss()
                    ARouter.getInstance()
                        .build(ARouterUtils.IndexActivity)
                        .navigation()
                    finish()
                }

                override fun onError(e: Throwable) {
                    ToastUtil.showToast(e.message)
                    mLoadingDialog.dismiss()
                }

            })
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        return /*true*/ if (KeyboardUtil.onKeyDown(keyCode, event, this)) true else super.onKeyDown(keyCode, event)
    }

    override fun doubleQuit(): Boolean = true
    override fun exit(): Boolean {
        try {
            if (isExit) {
                stopService(Intent(this, AppService::class.java))
//                stopService(Intent(this, RemoteService::class.java))
//                stopService(Intent(this, LocalService::class.java))
            }
        } catch (e: Exception) {
            d("退出失败:$e")
        }
        return super.exit()
    }


}